package com.atguigu.chapter05.transform;

import com.atguigu.bean.WaterSensor;
import org.apache.flink.api.java.functions.KeySelector;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.ProcessFunction;
import org.apache.flink.util.Collector;

/**
 * Author: Pepsi
 * Date: 2023/7/28
 * Desc:
 */
public class Flink10_process_noKey {
    public static void main(String[] args) {
        Configuration conf = new Configuration();
        conf.setInteger("rest.port",1000);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);
        env.setParallelism(2);

        DataStreamSource<WaterSensor> stream = env.fromElements(
                new WaterSensor("sensor_1", 1L, 10),
                new WaterSensor("sensor_1", 1L, 20),
                new WaterSensor("sensor_2", 1L, 30),
                new WaterSensor("sensor_1", 1L, 40),
                new WaterSensor("sensor_2", 1L, 50)
        );
        //当并行度为2的时候，他会分到两个分区里面，每个分区里面new了一个对象，所以就有两个sum，所以结果不对
        stream
                .process(new ProcessFunction<WaterSensor, String>() {
                    int sum = 0;
                    @Override
                    public void processElement(
                            WaterSensor value,  // 进来的每个数据
                            Context ctx,    // 上下文
                            Collector<String> out) throws Exception {
                        sum += value.getVc();
                        out.collect("总的水位和是："+sum);
                    }
                })
                .print();

/*        stream.keyBy(new KeySelector<WaterSensor, Integer>() {
            @Override
            public Integer getKey(WaterSensor value) throws Exception {
                return 1;
            }
        })
                .sum("vc").print();*/

        try {
            env.execute();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
